/**
 * Copyright (c) 2012 Nokia Corporation. 
 */

package com.nokia.example.tictactoe.console;

import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;

import com.nokia.mid.ui.CanvasGraphicsItem;

/**
 * Console for displaying application state messages on the screen.
 * Used for debugging purposes.
 */
public class Console
	extends CanvasGraphicsItem
	implements Log.Renderer
{
	// Members
	private Font _font = null;
	private TextWrapper _textWrapper;
	private boolean _minimized;
	
	public Console(int width, int height) {
		super(width, height);
		Log.setRenderer(this);
		_font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_ITALIC, Font.SIZE_SMALL);
		_textWrapper = TextWrapper.instance(_font, getWidth());
		_minimized = true;
	}

	/**
	 * From CanvasGraphicsItem.
	 */
	protected void paint(Graphics graphics) {
		graphics.setColor(0xeedddddd);
        graphics.setFont(_font);

        String[] entries = Log.instance().logEntries();
		final int x = 0;
		int y = 0;
		
		for (int i = Log.MAX_ENTRY_COUNT - 1; i >= 0; --i) {
			if (entries[i] == null) {
				continue;
			}
			
			try {
				_textWrapper.setText(entries[i]);
			}
			catch (IllegalArgumentException e) {
				System.out.println("Console::paint(): TextWrapper::setText() failed!");
				continue;
			}
			
			while (_textWrapper.hasMoreLines()) {
				graphics.drawString(_textWrapper.nextLine(), x, y, Graphics.TOP | Graphics.LEFT);
				y += _textWrapper.lineHeight();
			}
		}
	}

	/**
	 * From Log.IRenderer.
	 */
	public void onRenderRequest() {
		repaint();
	}
	
	/**
	 * Maximizes/minimizes the console.
	 * @param minimized If true, will minimize. Maximizes otherwise.
	 */
	public void setMinimized(boolean minimized) {
		if (_minimized != minimized) {
			_minimized = minimized;
			
			if (_minimized) {
				setSize(getWidth(), 10);
			}
			else {
				setSize(getWidth(), getHeight());
			}
		}
	}
}
